package com.ruoyi.iot.service;

import com.ruoyi.iot.config.MqttSubscribeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class MqttMessageHandlerFactory {

    @Resource
    private Map<String, MqttMessageHandler> messageHandlerMap;

    /**
     * 根据topic获取对应的MqttMessageHandler
     * @param topic
     * @return
     */
    public  MqttMessageHandler getMessageHandler(String topic) {

        for (Map.Entry<String, MqttMessageHandler> entry : messageHandlerMap.entrySet()) {
            MqttMessageHandler handler = entry.getValue();
            Class<?> handlerClass = handler.getClass();
            // 检查类上是否有MqttSubscribeService注解
            MqttSubscribeService annotation = handlerClass.getAnnotation(MqttSubscribeService.class);
            if (annotation != null) {
                // 将MQTT通配符转换为正则表达式
                String regex = convertMqttTopicToRegex(annotation.topic());
                // 进行正则匹配
                if (topic.matches(regex)) {
                    return handler;
                }
            }
        }
        return null;

/*
 使用stream写法
        return  messageHandlerMap.values().stream()
                .filter(h -> {
                    Class<?> handlerClass = h.getClass();
                    MqttSubscribeService annotation = handlerClass.getAnnotation(MqttSubscribeService.class);
                    if (annotation != null) {
                        String topicPattern = annotation.topic();
                        String regex =  convertMqttTopicToRegex(topicPattern);
                        return topic.matches(regex);
                    }
                    return false;
                })
                .findFirst()
                .orElse(null);
*/

    }


    /**
     * 将MQTT topic模式转换为正则表达式
     * @param mqttTopic MQTT topic模式，可能包含+和#
     * @return 对应的正则表达式
     */
    public static String convertMqttTopicToRegex(String mqttTopic) {
        // 使用正则表达式一次性替换所有特殊字符
        String regex = mqttTopic.replaceAll("([.$^\\[\\]()|{}])", "\\\\$1")
                .replace("+", "[^/]+")
                .replace("#", "[^/]*(?:/[^/]*)*");

        // 确保匹配整个字符串
        return "^" + regex + "$";
    }

}
